package com.cennac.ccbcar;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_ENABLE_BT = 1;

    private BluetoothAdapter mBluetoothAdapter;
    private Button btnBluetooth;
    private Button btnScan;
    private Button btnConnect;
    private TextView txtResult;
    private ListView lvBluetooth;
    private Button btnBluetoothScan;
    ArrayAdapter<String> adapter;


    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();


        // Initializes Bluetooth adapter.
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        btnBluetooth=findViewById(R.id.btnBluetooth);
        btnBluetooth.setOnClickListener(onClickListener);

        btnBluetooth.setText("蓝牙（"+(mBluetoothAdapter.isEnabled()?"开":"关")+"）");



        btnBluetoothScan=findViewById(R.id.btnBluetoothScan);

        txtResult=findViewById(R.id.txtResult);
        txtResult.setMovementMethod(ScrollingMovementMethod.getInstance());

        btnConnect=findViewById(R.id.btnConnect);

        btnScan=findViewById(R.id.btnScan);
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                lvBluetooth.
                Set<BluetoothDevice> bds= mBluetoothAdapter.getBondedDevices();
                txtResult.setText(txtResult.getText()+"--------共有"+bds.size()+"蓝牙设备--------"+"\n");
                for (BluetoothDevice bd:bds) {
                   bd.getName();
                    txtResult.setText(txtResult.getText()+bd.getName()+"\t"+bd.getAddress()+"\n");
                }
                txtResult.setText(txtResult.getText()+"-----------------------------------"+"\n\n");

                Toast.makeText(MainActivity.this,"蓝牙设备："+bds.size(),Toast.LENGTH_LONG).show();
            }
        });


//        mBluetoothAdapter.startLeScan(callback);
//        Set<BluetoothDevice> bds= mBluetoothAdapter.getBondedDevices();
//        Toast.makeText(MainActivity.this,"蓝牙设备："+bds.size(),Toast.LENGTH_LONG).show();

    }


    final BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
//            bluetoothDeviceArrayList.add(device);
//            Log.d(TAG, "run: scanning...");
        }
    };



    private void initViews(){

//        View view=View.inflate(MainActivity.this,R.layout.dialog_scan,null);
        lvBluetooth=findViewById(R.id.lvBluetooth);
//        setContentView(view);

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void btnConnectClick(View v){
        //                 dialog=new Dialog(MainActivity.this);
//                 dialog.setTitle("选择一个设备连接");
//                 dialog.show();
        AlertDialog.Builder builder=new AlertDialog.Builder(this);


        Set<BluetoothDevice> bds= mBluetoothAdapter.getBondedDevices();
//                String[] items= (String[]) bds.toArray();
//                String[] items= {"asdf","zxcv"};
        List<String> items= new ArrayList<>();
        for (BluetoothDevice bd:bds) {
            items.add(bd.getName()+"\t"+bd.getAddress());
//                    txtResult.setText(txtResult.getText()+bd.getName()+"\t"+bd.getAddress()+"\n");
        }
//                listDialog.setItems(items, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });

//                builder.setPositiveButton("扫描新设备", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });

//        builder.setView(R.layout.dialog_scan);

        View view = View.inflate(v.getContext(), R.layout.dialog_scan, null);
        builder.setView(view);

        lvBluetooth=view.findViewById(R.id.lvBluetooth);
        AlertDialog listDialog=builder.create();

        listDialog.setTitle("选择一个设备连接");

//        adapter=new ArrayAdapter<String>(this, android.R.layout.activity_list_item,items);
//        String [] list = new String []{"姓名:张三","性别：男","地址：重庆市沙坪坝区沙正街174号"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items);
        lvBluetooth.setAdapter(adapter);

        listDialog.show();
    }


    private View.OnClickListener onClickListener=new View.OnClickListener() {
        @Override
        public void onClick(View v){
            // Ensures Bluetooth is available on the device and it is enabled. If not,
            // displays a dialog requesting user permission to enable Bluetooth.
            if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
//                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                mBluetoothAdapter.enable();
                btnBluetooth.setText("蓝牙（开）");
                Toast.makeText(MainActivity.this,"蓝牙正在打开...",Toast.LENGTH_LONG).show();

            }else {
                mBluetoothAdapter.disable();
                btnBluetooth.setText("蓝牙（关）");
                Toast.makeText(MainActivity.this,"蓝牙正在关闭...",Toast.LENGTH_LONG).show();


            }

        }
    };
}
